

#import "SetViewControllor.h"

#import "ZFModalTransitionAnimator.h"
#import "SetLogoutCell.h"
#import <JPUSHService.h>
#import "AppDelegate.h"
#import "YBTabBarController.h"
#import "SetCell.h"
#import "BlackListVC.h"
#import <SDWebImage/SDImageCache.h>
#import "PubH5.h"
#import "YBDestroyAccount.h"
#import "YBPrivateVC.h"
#import "YBUserAuthVC.h"
@interface SetViewControllor ()<UITableViewDataSource,UITableViewDelegate> {
    int isNewBuid;//判断是不是最新版本
    CGFloat _cacheSize;
    
    NSMutableArray *_titleArray;
    
}
@property (nonatomic, strong) ZFModalTransitionAnimator *animator;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toppp;
@end
@implementation SetViewControllor
- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviView.hidden = YES;
    [BGSetting getBgSettingUpdate:NO maintain:NO eventBack:nil];
    double size = (double)[[SDImageCache sharedImageCache] totalDiskSize];
    _cacheSize = size /1024.0/1024.0;
    [self updateCache];
    
    if (self.toppp.constant<80) {
        self.toppp.constant += statusbarHeight;
    }
    self.automaticallyAdjustsScrollViewInsets = NO; self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.navigationBar.backgroundColor = RGB_COLOR(@"#F6F6F6", 1);
    self.navigationController.interactivePopGestureRecognizer.delegate = (id) self;
    
    self.view.backgroundColor = [UIColor blackColor];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.backgroundColor = Normal_Color;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

-(void)updateCache {
    NSString *judge_boudle = [NSBundle mainBundle].bundleIdentifier;
    NSString *aboutStr = YZMsg(@"关于我们");
    /*
    if ([judge_boudle isEqual:@"chatsifieds.app"]||[judge_boudle isEqual:@"com.ybdsp.video"]) {
        aboutStr = YZMsg(@"关于云视");
    }
    */
    NSString *hisBuild = [common ipa_ver];
    NSString *updateTitle = YZMsg(@"当前版本");
    NSString *updateDes = [NSString stringWithFormat:@"%@(%@)",[PublicObj getAppBuild],YZMsg(@"最新")];
    if (![[PublicObj getAppBuild] isEqual:hisBuild]) {
        //updateTitle = YZMsg(@"检查更新");
        updateDes = [NSString stringWithFormat:@"%@(%@)",[PublicObj getAppBuild],YZMsg(@"可更新")];
    }
    
    if ([PublicObj isUp]) {
        updateDes = [NSString stringWithFormat:@"%@",[PublicObj getAppBuild]];
    }
    
    NSString *cacheStr = [NSString stringWithFormat:@"%.1fM",_cacheSize];
    
    NSString *showLangStr = @"English";
    if ([lagType isEqual:ZH_CN]) {
        showLangStr = @"简体中文";
    }
    
    _titleArray = @[@{@"id":@"0",@"name":YZMsg(@"黑名单"),@"des":@"",@"switch":@"0"},
                    @{@"id":@"5",@"name":YZMsg(@"注销账号"),@"des":@"",@"switch":@"0"},
                    @{@"id":@"7",@"name":YZMsg(@"声音音效"),@"des":@"",@"switch":@"1"},
//                    @{@"id":@"8",@"name":YZMsg(@"语言切换"),@"des":showLangStr,@"switch":@"0"},
                    @{@"id":@"1",@"name":YZMsg(@"我的认证"),@"des":@"",@"switch":@"0"},
                    @{@"id":@"2",@"name":aboutStr,@"des":@"",@"switch":@"0"},
                    @{@"id":@"6",@"name":YZMsg(@"隐私政策"),@"des":@"",@"switch":@"0"},
                    @{@"id":@"3",@"name":updateTitle,@"des":updateDes,@"switch":@"0"},
                    @{@"id":@"4",@"name":YZMsg(@"清除缓存"),@"des":cacheStr,@"switch":@"0"},
    ].mutableCopy;
    
//    if ([[common getAuthSwitch]isEqual:@"0"]) {
//        [_titleArray removeObject:@{@"id":@"1",@"name":YZMsg(@"我的认证"),@"des":@"",}];
//    }
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    // 获取到是字节
    //double size = (double)[[SDImageCache sharedImageCache] getSize];
   
    self.navigationController.navigationBarHidden = YES;
    
    [self navtion];
    [self.tableView reloadData];
}
-(void)navtion{
    UIView *navtion = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 64+statusbarHeight)];
    navtion.backgroundColor = CellRow_Cor;
    UILabel *labels = [[UILabel alloc]init];
    labels.text = YZMsg(@"个性设置");
    [labels setFont:SYS_Font(17)];
    labels.textColor = [UIColor whiteColor];
    labels.frame = CGRectMake(0, 0+statusbarHeight,_window_width,84);
    labels.textAlignment = NSTextAlignmentCenter;
    [navtion addSubview:labels];
    UIButton *returnBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    returnBtn.tintColor = [UIColor whiteColor];
    UIButton *bigBTN = [[UIButton alloc]initWithFrame:CGRectMake(0, 0+statusbarHeight, _window_width/2, 64)];
    [bigBTN addTarget:self action:@selector(doReturn) forControlEvents:UIControlEventTouchUpInside];
    [navtion addSubview:bigBTN];
    returnBtn.frame = CGRectMake(10,22+statusbarHeight,40,40);[returnBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
    returnBtn.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    returnBtn.tintColor = [UIColor whiteColor];
    [returnBtn setImage:[UIImage imageNamed:@"pub_back"] forState:UIControlStateNormal];
    [returnBtn addTarget:self action:@selector(doReturn) forControlEvents:UIControlEventTouchUpInside];
    [navtion addSubview:returnBtn];
    UIButton *btnttttt = [UIButton buttonWithType:UIButtonTypeCustom];
    btnttttt.backgroundColor = [UIColor clearColor];
    [btnttttt addTarget:self action:@selector(doReturn) forControlEvents:UIControlEventTouchUpInside];
    btnttttt.frame = CGRectMake(0,0+statusbarHeight,100,64);
    [navtion addSubview:btnttttt];
    
    [self.view addSubview:navtion];
    
}
-(void)doReturn{    
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UIFont *font = SYS_Font(16);//[UIFont fontWithName:@"Heiti SC" size:15];
    if (indexPath.section == 0) {
        NSDictionary *subDic = _titleArray[indexPath.row];
        BOOL switchShow = [minstr([subDic valueForKey:@"switch"]) boolValue];
        SetCell *cell = [SetCell cellForTableView:tableView];
        cell.labContrName.text = minstr([subDic valueForKey:@"name"]);
        cell.labContrName.textColor = GrayText;
        cell.labContrName.font = font;
        cell.labDetail.text = minstr([subDic valueForKey:@"des"]);
        cell.labDetail.textColor = UIColor.whiteColor;
        cell.backgroundColor = cell.contentView.backgroundColor = CellRow_Cor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.arrowIV.hidden = switchShow;
        cell.switchBtn.hidden = !switchShow;
        cell.switchBtn.selected = [common getMsgVoiceSwitch];
        return cell;
    }else{
        SetLogoutCell *cell = [[NSBundle mainBundle]loadNibNamed:@"SetLogoutCell" owner:self options:nil].lastObject;
        cell.backgroundColor = cell.contentView.backgroundColor = CellRow_Cor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //判断当前分区返回分区行数
    if (section == 0 ) {
        return _titleArray.count;
    }
    else
    {
        return 1;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //返回分区数
    return 2;
}
- ( CGFloat )tableView:( UITableView *)tableView heightForHeaderInSection:( NSInteger )section
{
    if (section==1) {
        return 30;
    }else{
        return 0.01;
    }
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger) section
{
    return 1;
}
//点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        NSDictionary *subDic = _titleArray[indexPath.row];
        int idInt = [minstr([subDic valueForKey:@"id"]) intValue];
        switch (idInt) {
            case 0:{
                //黑名单
                BlackListVC *blac = [[BlackListVC alloc]init];
                [self.navigationController pushViewController:blac animated:YES];
            }break;
            case 1:{
                //我的认证
                
                /*
                PubH5 *h5 = [[PubH5 alloc]init];
                h5.url = [NSString stringWithFormat:@"%@/Appapi/Auth/index?uid=%@&token=%@",h5url,[Config getOwnID],[Config getOwnToken]];
                [self.navigationController pushViewController:h5 animated:YES];
                */
                YBUserAuthVC *authVC = [[YBUserAuthVC alloc]init];
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:authVC animated:YES];
                
            }break;
            case 2:{
                //关于云视
                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSNumber *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
                NSString *build = [NSString stringWithFormat:@"%@",app_build];
                PubH5 *h5vc = [[PubH5 alloc]init];
                h5vc.url = [NSString stringWithFormat:@"%@/appapi/about/index?version=%@&uid=%@&token=%@&device=%@&ios=1",h5url,build,[Config getOwnID],[Config getOwnToken],[PublicObj iphoneType]];
                [self.navigationController pushViewController:h5vc animated:YES];
                
            }break;
            case 3:{
                //版本更新
                [self getbanben];
            }break;
            case 4:{
                [StorageConfig clearResTime];
                //清除缓存
                //[[SDImageCache sharedImageCache] clearDisk];
                [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
                    
                }];
                // 设置为0
                //NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/ImageCache"];
                // 获取到是字节
                //double size = (double)[[SDImageCache sharedImageCache] getSize];
                double size = (double)[[SDImageCache sharedImageCache] totalDiskSize];
                _cacheSize = size /1024.0/1024.0;
                [MBProgressHUD showPop:YZMsg(@"清除成功！")];
                [self updateCache];
                [_tableView reloadData];
            }break;
            case 5:{
                //注销账号
                YBDestroyAccount *desVC = [[YBDestroyAccount alloc]init];
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:desVC animated:YES];
            }break;
            case 6:{
                //隐私政策
                YBPrivateVC *desVC = [[YBPrivateVC alloc]init];
                desVC.hideBottom = YES;
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:desVC animated:YES];
            }break;
            case 8:{
                //语言设置
                [self setLanguage];
            }break;
            default:{
                
            }break;
        }
        
    }else if (indexPath.section == 1){
        [self quitAlert];
    }
    
}
-(void)setLanguage {
    YBWeakSelf;
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:nil];
    [sheet addActionWithType:RKSheet_Default andTitle:@"简体中文" complete:^{
        [weakSelf chageLang:ZH_CN];
    }];
    [sheet addActionWithType:RKSheet_Default andTitle:@"English" complete:^{
        [weakSelf chageLang:EN];
    }];
    [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
    }];
    [sheet showSheet];
}
-(void)chageLang:(NSString *)curLang {
    [[YBLanguageTools shareInstance] resetLanguage:curLang withFrom:@"setvc"];
    
}

-(void)getbanben{
    if ([PublicObj isUp]) {
        return;
    }
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSNumber *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];//本地
    NSNumber *build = (NSNumber *)[common ipa_ver];//远程
    NSComparisonResult r = [app_build compare:build];
    if (r == NSOrderedAscending || r == NSOrderedDescending) {//可改为if(r == -1L)
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[common app_ios]]];
    }else if(r == NSOrderedSame) {//可改为if(r == 0L)
        [MBProgressHUD showPop:YZMsg(@"当前已是最新版本")];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (void)clearTmpPics
{
    //[[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache]clearDiskOnCompletion:^{
        
    }];
    
}
//MARK:-设置tableivew分割线
-(void)setTableViewSeparator
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPa
{
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
-(void)quitAlert {
    YBWeakSelf;
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:@""];
    [sheet addActionWithType:RKSheet_FunPink andTitle:YZMsg(@"继续退出") complete:^{
        [weakSelf quitLogin];
    }];
    [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
    }];
    [sheet showSheet];
}
-(void)quitLogin
{
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"hideHomeVideoRed" object:nil];
    //清空所有缓存
    //NSString*appDomain = [[NSBundle mainBundle]bundleIdentifier];
    //[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
   
    [PublicObj resetUserToVisitor];
    
    YBTabBarController *root = [[YBTabBarController alloc]initWithAlert:NO];
    YBNavigationController *navroot = [[YBNavigationController alloc]initWithRootViewController:root];
    UIApplication *app =[UIApplication sharedApplication];
    AppDelegate *app2 = (AppDelegate*)app.delegate;
    [app2.window removeAllSubViews];
    app2.window.rootViewController = navroot;
    
}

@end

